import types from "../types";
import api from "@/api.js";
import storage from "@/utils/storage.js";

const state = {
  csrfToken: "",
  accessToken: "",
  profile: {},
};

const getters = {
  profile: state => state.profile,
  studentId: state => state.profile.studentId,
  name: state => state.profile.name,
  level: state => state.profile.level || state.profile.role,
  accessToken: state => state.accessToken,
  noToken: state => !state.accessToken,
  hasToken: state => !!state.accessToken,
  csrfToken: state => state.csrfToken,
};

const mutations = {
  [types.CHANGE_PROFILE](state, profile) {
    state.profile = profile;
  },
  [types.CHANGE_ACCESS_TOKEN](state, { accessToken }) {
    state.accessToken = accessToken;
  },
  [types.CHANGE_USER_LEVEL](state, { level }) {
    state.level = level;
  },
  [types.CHANGE_CSRF_TOKEN](state, { token }) {
    state.csrfToken = token;
  }
};

const actions = {
  async getCsrfToken({ commit }) {
    const { data } = await api.getCsrfToken();
    commit(types.CHANGE_CSRF_TOKEN, data);
  },
  async signIn({ commit, dispatch }, payload) {
    const { data } = await api.login(payload);
    let accessToken = data.data["access_token"] || "";
    storage.set("TOKEN", data.data);
    storage.set("USER", payload.id);
    commit(types.CHANGE_ACCESS_TOKEN, { accessToken });
    dispatch("updateUserProfile");
  },
  async signOut({ dispatch }) {
    try {
      await api.logout({
        userId: storage.get("USER")
      });

      dispatch("clearLocalData");
    } catch (error) {
      console.log(error);
    }

  },
  async refreshToken({ getters, commit }) {
    // TODO
  },
  async updateUserProfile({ getters, commit }) {
    if (getters.noToken) {
      return;
    }
    const { data } = await api.getMember({
      id: storage.get("USER")
    });
    commit(types.CHANGE_PROFILE, data.data);
  },
  async clearLocalData({ commit }) {
    console.log("clearLocalData");
    commit(types.CHANGE_ACCESS_TOKEN, {
      accessToken: ""
    });
    commit(types.CHANGE_PROFILE, {});
    storage.clear();
  }
};

export default {
  state,
  mutations,
  getters,
  actions
};
